package com.langsin.my0628;

import com.langsin.bean.User;
import com.langsin.loujianguo.mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.InputStream;

/**
 * @author LQWQK
 * @version 1.0
 * @since 2022-06-28 09:20:46
 */
public class LqwqkTest {

    // 二级缓存 需要 我们的对象 能 序列化   , 二级缓存 有可能存入到硬盘里的.
    @Test
    public void testCache2() throws Exception{
        // mybatis一级缓存是 存在 sqlSession的 内存 map里的 .
        InputStream stream = Resources.getResourceAsStream("mybatis.xml");
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sessionFactory = builder.build(stream);
        SqlSession sqlSession1 = sessionFactory.openSession();
        // 第一个会话的查询
        UserMapper mapper1 = sqlSession1.getMapper(UserMapper.class);
        User user1 = mapper1.queryById(702);
        System.out.println(user1);
        sqlSession1.close();

        try{Thread.sleep(2000);}catch(Exception e){e.printStackTrace();}
        System.out.println("休眠2s时间到!");

        // 第二个会话
        SqlSession sqlSession2 = sessionFactory.openSession();
        UserMapper mapper2 = sqlSession2.getMapper(UserMapper.class);
        User user2 = mapper2.queryById(702);
        System.out.println(user2);
        sqlSession2.close();
    }

    @Test
    public void testCache1() throws Exception{
        // mybatis一级缓存是 存在 sqlSession的 内存 map里的 .
        InputStream stream = Resources.getResourceAsStream("mybatis.xml");
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sessionFactory = builder.build(stream);
        SqlSession sqlSession = sessionFactory.openSession();
        // 查询第一次
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        User user = userMapper.queryById(702);
        System.out.println(user);

        try{Thread.sleep(2000);}catch(Exception e){e.printStackTrace();}

        // 同一个sqlsession 查询第二次
        User user2 = userMapper.queryById(702);
        System.out.println(user2);

        // 如果同一个会话对象 进行了 增删改 ,缓存就会失效.
    }
}
